package org.example.springboot.utils;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

import com.aliyun.oss.*;

@Component
public class AliOSSUtils {
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    private String accessKeyId = "LTAI5tC4vw26KqbJFxYAQprv";
    private String accessKeySecret = "uYV3d86BAB22u8cOUIlIIwI9bYteXo";
    // 填写Bucket名称
    private String bucketName = "upload-peiking";

    public String upload(MultipartFile file) throws IOException {
        //获取文件上传输入流
        InputStream inputStream = file.getInputStream();
        //避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        //System.currentTimeMillis()加上系统时间戳 相当于给文件名加上一个唯一标识
        String fileName = System.currentTimeMillis() + "_" + originalFilename; //文件名为：20257121134_xxx.png
        //上传文件到OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);
        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] +  "/" + fileName;
        //关闭ossClient
        ossClient.shutdown();
        return url;//把上传到oss的路径返回
    }

}
